
package bibliotheque.server;

import bibliotheque.transaction.Transaction;
import bibliotheque.transaction.TransactionId;
import bibliotheque.wave.WaveAction;
import bibliotheque.wave.WaveAgent;

public class PreSelectionAction extends WaveAction{
    
    private TransactionId id;
    
    public PreSelectionAction(TransactionId id) {
        this.id = id;
    }
    
    public TransactionId GetId() {
        return(this.id);
    }
    
    public void PropagateBefore(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            Transaction t;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.STOP) throw new Exception("Selection failed cause server state is stopped.");
               
                if(server.state == Server.State.START) server.transaction_manager.PreSelectInit(this.id);
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void LocalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            try {
                server.mutex.acquireUninterruptibly();
                
                if(server.state == Server.State.STOPPING && server.transaction_manager.GetNbUseDocument() == 0 && server.GetNbWaves() == 0) {
                    server.state = Server.State.STOP;
                    server.StateChanged(server.state.toString());
                }
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
            } finally {
                server.mutex.release();
            }
        }
    }
    
    public void GlobalEnd(WaveAgent agent) throws Exception {
        if (agent instanceof Server) {
            Server server = (Server)agent;
            Transaction t;
            try {
                server.mutex.acquireUninterruptibly();
                if(server.state == Server.State.STOP) throw new Exception("Selection failed cause server state is stopped.");
               
                server.Initiate(new SelectionAction(this.id));
            } catch (Exception ex) {
                server.ErrorOccured(ex.getMessage());
                throw ex;
            } finally {
                server.mutex.release();
            }
        }
    }
}
